package com.cheyunkeji.er.activity.auction;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyunkeji.er.adapter.MyBaseAdapter;
import com.cheyunkeji.er.adapter.auction.NotificationItemAdapter;
import com.cheyunkeji.er.app.PushMsgManager;
import com.cheyunkeji.er.base.BaseActivity;
import com.cheyunkeji.er.bean.auction.NotifyItemBean;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.SwipeLayout;
import com.cheyunkeji.er.view.TopBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class NotificationActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener, AdapterView.OnItemClickListener {


    //    每页数据量
    private static final int COUNTS_PER_PAGE = 10;
    //    当前列表状态 STATE_REFRESH : 下拉刷新 ，STATE_LOADMORE : 上拉加载更多
    private static int CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.ll_empty_content)
    LinearLayout llEmptyContentDisplay;
    @BindView(R.id.swipe_target)
    ListView swipeTarget;
    @BindView(R.id.swipe_layout)
    SwipeLayout swipeLayout;
    @BindView(R.id.activity_xun_jia_notify)
    LinearLayout activityXunJiaNotify;
    @BindView(R.id.tv_item_count)
    TextView tvItemCount ;

    private int CURRENT_LOAD_PAGE = 1;
    private String TAG = NotificationActivity.class.getSimpleName();

    private ArrayList<NotifyItemBean> dataList;
    private MyBaseAdapter adapter;

    //    当前页面类型
    private int PAGE_TYPE = Constants.PAGE_XUNJIA;

    private Handler uiRefreshHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {

                onRefreshSuccessed((ArrayList<NotifyItemBean>) msg.obj);
            } else {

                onLoadMoreSuccessed((ArrayList<NotifyItemBean>) msg.obj);
            }
        }
    };


    @Override
    protected void init() {

        setContentView(R.layout.er_activity_notification);
        ButterKnife.bind(this);
        PAGE_TYPE = getIntent().getIntExtra(Constants.NOTIFICATION_PAGE_TYPE, PushMsgManager.MSG_TYPE_XUNJIA);

        dataList = new ArrayList<>();
        adapter = new NotificationItemAdapter(dataList, this);
        swipeTarget.setAdapter(adapter);

    }


    @Override
    protected void initView() {

        vTopbar.setLeftBack();

        switch (PAGE_TYPE) {

            case PushMsgManager.MSG_TYPE_XUNJIA:
                vTopbar.setTitle("询价通知");
                break;
            case PushMsgManager.MSG_TYPE_PAIMAI:
                vTopbar.setTitle("拍卖通知");
                break;
            case PushMsgManager.MSG_TYPE_ZHONGBIAO:
                vTopbar.setTitle("得标通知");
                break;
            case PushMsgManager.MSG_TYPE_LIUBIAO:
                vTopbar.setTitle("流标通知");
                break;
            case PushMsgManager.MSG_TYPE_YUZHAN:
                vTopbar.setTitle("预展通知");
                break;

            default:
                break;

        }

        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setOnLoadMoreListener(this);
        swipeTarget.setOnItemClickListener(this);
    }

    @Override
    protected void initData() {

    }

    public void setItemCount(int itemCount ){
        tvItemCount.setText(String.format( "共%1$s条数据" , String.valueOf(itemCount)));
    }

    public void loadNotifyMsgList(int page, int rows) {

        HashMap<String, String> params = new HashMap<>();
//        params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("page", String.valueOf(page));
        params.put("rows", String.valueOf(rows));
        params.put("notice_type", String.valueOf(PAGE_TYPE));

        ApiClient.postForm(HttpConstants.GETUI_NOTIFICATION_MSG_LIST, params, new RespCallback<List<NotifyItemBean>>() {

            @Override
            protected void onRequestFailed(String msg) {
                SToast.show(msg);
            }

            @Override
            protected void onMsgCount(int rows) {
                super.onMsgCount(rows);
                setItemCount(rows);
            }

            @Override
            protected void onSuccess(List<NotifyItemBean> data) {

                Log.e(TAG, "onSuccess: " + data.size()) ;
                Log.e(TAG, "onSuccess: CURRENT PAGE INDEX : " + CURRENT_LOAD_PAGE) ;

                Message msg = uiRefreshHandler.obtainMessage() ;
                msg.obj = data ;
                uiRefreshHandler.sendMessage(msg) ;

            }

            @Override
            public void onError(Exception e) {
                super.onError(e);

                if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_REFRESH) {
                    swipeLayout.endRefresh();
                } else if (CURRENT_REFRESH_STATE == SwipeLayout.STATE_LOADMORE) {
                    swipeLayout.endLoadMore();
                }
            }

        });

    }


    private void hideEmptyView() {

        //swipeLayout.setVisibility(View.VISIBLE);
        llEmptyContentDisplay.setVisibility(View.INVISIBLE);

    }


    private void showContentEmptyView() {

        //swipeLayout.setVisibility(View.INVISIBLE);
        llEmptyContentDisplay.setVisibility(View.VISIBLE);
    }

    private void onRefreshSuccessed(ArrayList<NotifyItemBean> newList) {

        if (newList != null && newList.size() != 0) {

            hideEmptyView();
            dataList.clear();
            dataList.addAll(newList);
            adapter.notifyDataSetChanged();
            CURRENT_LOAD_PAGE++;

        } else if (newList.size() == 0) {
            showContentEmptyView();
            dataList.clear();
            adapter.notifyDataSetChanged();
        }
        swipeLayout.endRefresh();

    }


    /**
     * 上拉加载成功刷新
     *
     * @param newList
     */
    private void onLoadMoreSuccessed(ArrayList<NotifyItemBean> newList) {

        if (newList != null) {

            if (newList.size() != 0) {

                swipeLayout.endLoadMore();
                dataList.addAll(newList);
                adapter.notifyDataSetChanged();
                CURRENT_LOAD_PAGE++;

            } else {

                swipeLayout.endLoadMore();
                swipeLayout.setLoadMoreEnabled(false);

            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        swipeLayout.setRefreshing(true);
        onRefresh();
    }

    @Override
    public void onRefresh() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_REFRESH;
        CURRENT_LOAD_PAGE = 1;
        loadNotifyMsgList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE);
        swipeLayout.setLoadMoreEnabled(true);
    }

    @Override
    public void onLoadMore() {
        CURRENT_REFRESH_STATE = SwipeLayout.STATE_LOADMORE;
        loadNotifyMsgList(CURRENT_LOAD_PAGE, COUNTS_PER_PAGE);
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(this, XunJiaDetailActivity.class);

        switch (PAGE_TYPE) {

            case PushMsgManager.MSG_TYPE_XUNJIA:
                intent.putExtra(Constants.DETAIL_RESULT_TYPE, Constants.RESULT_TYPE_BAOJIA_WAIT);
                intent.putExtra("rid", dataList.get(position).getPayload().getKey_id());
                startActivity(intent);
                break;
            case PushMsgManager.MSG_TYPE_PAIMAI:
                intent.putExtra(Constants.DETAIL_RESULT_TYPE, Constants.RESULT_TYPE_AUCTION_ON_PROCESS);
                intent.putExtra("tid", dataList.get(position).getPayload().getKey_id());
                startActivity(intent);
                break;
            case PushMsgManager.MSG_TYPE_ZHONGBIAO:
                intent.putExtra(Constants.DETAIL_RESULT_TYPE, Constants.RESULT_TYPE_AUCTION_GOT);
                intent.putExtra("tid", dataList.get(position).getPayload().getKey_id());
                startActivity(intent);
                break;
            case PushMsgManager.MSG_TYPE_LIUBIAO:
                intent.putExtra(Constants.DETAIL_RESULT_TYPE, Constants.RESULT_TYPE_AUCTION_LOST);
                intent.putExtra("tid", dataList.get(position).getPayload().getKey_id());
                startActivity(intent);
                break;
            case PushMsgManager.MSG_TYPE_YUZHAN:
                intent.putExtra(Constants.DETAIL_RESULT_TYPE, Constants.RESULT_TYPE_AUCTION_PREPROCESS);
                intent.putExtra("tid", dataList.get(position).getPayload().getKey_id());
                startActivity(intent);
                break;

            default:
                break;

        }
    }
}
